package org.example.rubbish.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.example.rubbish.common.PageResult;
import org.example.rubbish.entity.ForumPost;
import org.example.rubbish.mapper.ForumMapper;
import org.example.rubbish.service.ForumService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class ForumServiceImpl implements ForumService {

    @Autowired
    private ForumMapper forumMapper;

    @Override
    public PageResult<ForumPost> getForumPosts(Integer page, Integer size, String title, String author, String status) {
        return getForumPosts(page, size, title, author, status, null, null, null);
    }

    @Override
    public PageResult<ForumPost> getForumPosts(Integer page, Integer size, String title, String author,
                                               String status, String province, String city, String district) {
        PageHelper.startPage(page, size);

        Map<String, Object> params = new HashMap<>();
        if (StringUtils.hasText(title)) {
            params.put("title", "%" + title + "%");
        }
        if (StringUtils.hasText(author)) {
            params.put("author", "%" + author + "%");
        }
        if (StringUtils.hasText(status)) {
            params.put("status", status);
        }
        // 行政区域筛选
        if (StringUtils.hasText(province)) {
            params.put("province", province);
        }
        if (StringUtils.hasText(city)) {
            params.put("city", city);
        }
        if (StringUtils.hasText(district)) {
            params.put("district", district);
        }

        List<ForumPost> posts = forumMapper.selectForumPosts(params);
        PageInfo<ForumPost> pageInfo = new PageInfo<>(posts);

        return PageResult.success(pageInfo.getList(), pageInfo.getTotal());
    }

    @Override
    public PageResult<ForumPost> searchPostsByBounds(Integer page, Integer size,
                                                     Double swLat, Double swLng,
                                                     Double neLat, Double neLng,
                                                     String title, String author, String status) {
        PageHelper.startPage(page, size);

        Map<String, Object> params = new HashMap<>();
        // 矩形边界参数
        params.put("swLat", swLat);
        params.put("swLng", swLng);
        params.put("neLat", neLat);
        params.put("neLng", neLng);

        if (StringUtils.hasText(title)) {
            params.put("title", "%" + title + "%");
        }
        if (StringUtils.hasText(author)) {
            params.put("author", "%" + author + "%");
        }
        if (StringUtils.hasText(status)) {
            params.put("status", status);
        }

        List<ForumPost> posts = forumMapper.selectPostsByBounds(params);
        PageInfo<ForumPost> pageInfo = new PageInfo<>(posts);


        return PageResult.success(pageInfo.getList(), pageInfo.getTotal());
    }

    @Override
    public Map<String, Object> getNationalPostDistribution() {
        Map<String, Object> result = new HashMap<>();

        // 基础统计
        result.put("totalPosts", forumMapper.countTotalPosts());
        result.put("postsWithLocation", forumMapper.countPostsWithLocation());
        result.put("postsWithoutLocation", forumMapper.countPostsWithoutLocation());

        // 按省份分布
        List<Map<String, Object>> provinceDistribution = forumMapper.getProvinceDistribution();
        result.put("provinceDistribution", provinceDistribution);

        // 热门城市TOP10
        List<Map<String, Object>> topCities = forumMapper.getTopCities(10);
        result.put("topCities", topCities);

        // 区域密度分析
        List<Map<String, Object>> regionDensity = forumMapper.getRegionDensity();
        result.put("regionDensity", regionDensity);

        // 时间趋势（近30天发帖量）
        List<Map<String, Object>> recentTrend = forumMapper.getRecentPostTrend(30);
        result.put("recentTrend", recentTrend);

        return result;
    }

    @Override
    public List<Map<String, Object>> getRegionStatsReport(String level) {
        if ("city".equals(level)) {
            return forumMapper.getCityStatsReport();
        } else if ("district".equals(level)) {
            return forumMapper.getDistrictStatsReport();
        } else {
            return forumMapper.getProvinceStatsReport();
        }
    }

    @Override
    public List<Map<String, Object>> getForumHeatmapData(String status, String province, String city) {
        Map<String, Object> params = new HashMap<>();
        if (StringUtils.hasText(status)) {
            params.put("status", status);
        }
        if (StringUtils.hasText(province)) {
            params.put("province", province);
        }
        if (StringUtils.hasText(city)) {
            params.put("city", city);
        }
        return forumMapper.selectForumHeatmapData(params);
    }

    @Override
    public ForumPost createForumPost(ForumPost forumPost) {
        forumPost.setCreateTime(LocalDateTime.now());
        forumPost.setUpdateTime(LocalDateTime.now());
        forumPost.setViewCount(0);
        forumPost.setLikeCount(0);
        forumPost.setCommentCount(0);

        forumMapper.insertForumPost(forumPost);
        return forumPost;
    }

    @Override
    public ForumPost updateForumPost(ForumPost forumPost) {
        forumPost.setUpdateTime(LocalDateTime.now());
        forumMapper.updateForumPost(forumPost);
        return forumMapper.selectForumPostById(forumPost.getId());
    }

    @Override
    public void deleteForumPost(Long id) {
        forumMapper.deleteForumPost(id);
    }

    @Override
    public void batchDeleteForumPosts(List<Long> ids) {
        forumMapper.batchDeleteForumPosts(ids);
    }

    @Override
    public void updateForumPostStatus(Long id, String status) {
        ForumPost post = new ForumPost();
        post.setId(id);
        post.setStatus(status);
        post.setUpdateTime(LocalDateTime.now());
        forumMapper.updateForumPostStatus(post);
    }

    @Override
    public Object getForumStats() {
        Map<String, Object> stats = new HashMap<>();
        stats.put("totalPosts", forumMapper.countTotalPosts());
        stats.put("publishedPosts", forumMapper.countPostsByStatus("PUBLISHED"));
        stats.put("draftPosts", forumMapper.countPostsByStatus("DRAFT"));
        stats.put("pendingPosts", forumMapper.countPostsByStatus("PENDING"));
        stats.put("deletedPosts", forumMapper.countPostsByStatus("DELETED"));
        stats.put("totalViews", forumMapper.sumTotalViews());
        stats.put("totalLikes", forumMapper.sumTotalLikes());
        stats.put("totalComments", forumMapper.sumTotalComments());
        stats.put("postsWithLocation", forumMapper.countPostsWithLocation());
        return stats;
    }
}